/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.myapp.struts.personal;

import hibernate.CuentasHasClientes;
import hibernate.Tarjetas;
import hibernate.TarjetasDAO;
import java.util.Iterator;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import util.Mail;

/**
 *
 * @author Nacho
 */
public class ModificarTarjetaAction extends org.apache.struts.action.Action {

    /* forward name="success" path="" */
    private static final String SUCCESS = "success";
    private static final String PIN = "pin";

    /**
     * This is the action called from the Struts framework.
     *
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {

        ModificarTarjetaForm mod = (ModificarTarjetaForm) form;
        TarjetasDAO dao = new TarjetasDAO();

        // reestablecemos el pin de la tarjeta y mandamos un email
        if (request.getParameter("pin") != null) {
            String pin = "";
            for (int k = 0; k < 4; k++) {
                Random rand = new Random();
                pin = pin + String.valueOf(rand.nextInt(10));

            }
            Tarjetas tarjeta = dao.get(mod.getPkTarjeta());
            tarjeta.setPin(pin);
            dao.update(tarjeta);
            Iterator it = tarjeta.getCuentas().getCuentasHasClienteses().iterator();
            while (it.hasNext()) {
                CuentasHasClientes CC = (CuentasHasClientes) it.next();
                if (CC.getTipoCliente().equals("titular")) {
                   // Mail.enviarMail(CC.getClientes().getEmail(), "Su PIN ha sido reestablecido", "Estimado Cliente/a, le informamos que el nuevo PIN de su tarjeta número " + tarjeta.getNumero() + " es " + pin + ".");
                }
            }
            request.setAttribute("msg", "El pin de la tarjeta ha sido reestablecido y ha sido enviado por e-mail.");
            return mapping.findForward(PIN);
        }
        HttpSession session = request.getSession();
        Tarjetas tarjeta = dao.get(mod.getPkTarjeta());
        request.setAttribute("tarjeta", tarjeta);
        session.setAttribute("tarjeta", tarjeta);
        
        return mapping.findForward(SUCCESS);
    }
}
